# coding=utf-8
# 全世界最帅的帅哥
from flask import request, current_app
from sqlalchemy.exc import OperationalError, SQLAlchemyError
from ysgg1_club_comment.modules import db
from ysgg1_club_comment.utils.fbmsg import FBMsg
from ysgg1_club_comment.modules.auth_role_permission import AuthRolePermission


def create_role_permission_view():
    try:
        request_json = request.get_json()
        role_id = request_json.get('roleId')
        if not role_id:
            return FBMsg.error_param()
        permission_id_list = request_json.get('permissionIdList')
        if len(permission_id_list) <= 100:
            role_permission_list = []
            for permission_id in permission_id_list:
                role_permission = AuthRolePermission(role_id=role_id, permission_id=permission_id)
                role_permission_list.append(role_permission)
            db.session.add_all(role_permission_list)
            db.session.commit()
            current_app.logger.info("插入role_permission成功")
            return {"code": 200, "success": True, "message": "插入role_permission成功"}

        else:
            for permission_id in permission_id_list:
                role_permission = AuthRolePermission(role_id=role_id, permission_id=permission_id)
                db.session.add(role_permission)
            db.session.commit()
            current_app.logger.info("插入role_permission成功")
            return {"code": 200, "success": True, "message": "插入role_permission成功"}

    except (Exception, OperationalError, SQLAlchemyError) as e:
        current_app.logger.error(e.__str__())
        db.session.rollback()
        return FBMsg.create_role_permission_error_message()